//
//  LoginViewController.swift
//  DiDiRecycle
//
//  Created by abb on 16/7/6.
//  Copyright © 2016年 abb. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
import IQKeyboardManagerSwift
class LoginViewController: AbbBaseViewController {
    
    /// 电话号码
    var phoneNumber: String?
    /// 区号
    var zoneCode: String = "86"
    /// 验证码
    var password: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 1.加载UI
        setupUI()
    }
    
    override var userTransparentNavigationBar: Bool {
        return true
    }
    
    /**
     开始倒计时
     */
    func beginCountdown(){
        // 倒计时时间
        var timeout = 30
        // 创建一个默认队列
        let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
        // 创建一个定时器类型的调度源
        let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue)
        // 设置定时器属性
        dispatch_source_set_timer(timer, dispatch_walltime(nil, 0), UInt64(1.0) * NSEC_PER_SEC, 0)
        // 设置事件
        dispatch_source_set_event_handler(timer!, {() -> Void in
            if timeout <= 0 {// 倒计时结束,关闭
                // 取消源
                dispatch_source_cancel(timer)
                // 在主线程中修改UI
                dispatch_async(dispatch_get_main_queue(), {
                    self.getSMSBtn.layer.borderColor = UIColor.blackColor().CGColor
                    self.getSMSBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
                    self.getSMSBtn.setTitle("获取短信验证码", forState: .Normal)
                    self.getSMSBtn.userInteractionEnabled = true
                })
            }
            else {
                // 在主线程中修改UI
                dispatch_async(dispatch_get_main_queue(), {
                    self.getSMSBtn.layer.borderColor = UIColor.grayColor().CGColor
                    self.getSMSBtn.setTitleColor(UIColor.grayColor(), forState: .Normal)
                    self.getSMSBtn.setTitle("\(timeout)秒后重新发送", forState: .Normal)
                    self.getSMSBtn.userInteractionEnabled = false
                })
            }
            // 时间减一
            timeout -= 1
        })
        // 执行
        dispatch_resume(timer)
    }
    /**
     获取验证码
     */
    func getSMS() {
        // 键盘消失
        IQKeyboardManager.sharedManager().resignFirstResponder()
        // 赋值
//        self.phoneNumber = userView.phoneNumber
//        zoneCode = userView.zoneCode
        // 获取验证码
        SMSSDK.getVerificationCodeByMethod(SMSGetCodeMethodSMS, phoneNumber: phoneNumber, zone: zoneCode, customIdentifier: nil) { (error) in
            // 错误判断
            if (error == nil) {
                print("获取验证码成功")
                // 倒计时
                self.beginCountdown()
            }
            else {
                print("错误信息:\(error)")
                SVProgressHUD.showErrorWithStatus("网络错误,请重试")
            }
            
        }
    }
    /**
     登录
     */
    func LoginClick() {
        // 键盘消失
        IQKeyboardManager.sharedManager().resignFirstResponder()
        // 验证验证码
        User.loadUserBySms(phoneNumber!, zone: zoneCode, code: password!) { (model,resultCode,error) in
            if model != nil {// 成功获取
                // 归档模型
                model?.saveAccount()
                // 判断是否是新用户
                if resultCode == 0 {
                    NSNotificationCenter.defaultCenter().postNotificationName(ABBRootViewControllerKey, object: true)
                } else {
                    // TODO: - 完善登录信息
                    let vc = SetUserInfoViewController(userModel: model!)
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                
            } else {
                SVProgressHUD.showErrorWithStatus(error)
            }
        }
    }
    func pushToLoginPasswordViewController() {
        let vc = LoginPasswordViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    /**
     加载ui
     */
    private func setupUI() {
        
        // 1.添加子控件
        view.addSubview(logoImageView)
        view.addSubview(userView)
        view.addSubview(passwordView)
        view.addSubview(loginBtn)
        view.addSubview(getSMSBtn)
        view.addSubview(orSplitLineLeft)
        view.addSubview(orSplitLineRight)
        view.addSubview(orLabel)
        view.addSubview(userAgreementBtn)
        view.addSubview(passwordLoginBtn)
        // 2.布局子控件
        logoImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(30)
        }
        userView.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.centerY.equalTo(view.snp_centerY).multipliedBy(0.8)
            make.width.equalTo(self.view).multipliedBy(0.83)
            make.height.equalTo(42)
        }
        passwordView.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalTo(userView.snp_bottom).offset(20)
            make.width.equalTo(self.view).multipliedBy(0.83)
            make.height.equalTo(42)
        }
        loginBtn.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalTo(passwordView.snp_bottom).offset(80)
            make.width.equalTo(self.view).multipliedBy(0.85)
            make.height.equalTo(42)
            
        }
        // 获取验证码按钮
        getSMSBtn.snp_makeConstraints(closure: { (make) in
            make.right.equalTo(passwordView.snp_right).offset(-5)
            make.centerY.equalTo(passwordView)
        })
        // 分割线
        orSplitLineLeft.snp_makeConstraints { (make) in
            make.width.equalTo(self.view).multipliedBy(0.47)
            make.left.equalTo(self.view)
            make.centerY.equalTo(self.view).multipliedBy(1.8)
            make.height.equalTo(0.5)
        }
        orSplitLineRight.snp_makeConstraints { (make) in
            make.width.equalTo(self.view).multipliedBy(0.47)
            make.right.equalTo(self.view)
            make.centerY.equalTo(self.view).multipliedBy(1.8)
            make.height.equalTo(0.5)
        }
        orLabel.snp_makeConstraints { (make) in
            make.left.equalTo(orSplitLineLeft.snp_right)
            make.right.equalTo(orSplitLineRight.snp_left)
            make.centerY.equalTo(orSplitLineLeft)
        }
        userAgreementBtn.snp_makeConstraints { (make) in
            make.top.equalTo(orSplitLineLeft).offset(5)
            make.left.equalTo(self.view).offset(15)
            make.bottom.equalTo(self.view).offset(-5)
        }
        passwordLoginBtn.snp_makeConstraints { (make) in
            make.top.equalTo(orSplitLineRight).offset(5)
            make.right.equalTo(self.view).offset(-15)
            make.bottom.equalTo(self.view).offset(-5)
        }

        
        // 3.添加按钮监听
        loginBtn.addTarget(self, action: #selector(LoginClick), forControlEvents: .TouchUpInside)
        getSMSBtn.addTarget(self, action: #selector(getSMS), forControlEvents: .TouchUpInside)
        passwordLoginBtn.addTarget(self, action: #selector(pushToLoginPasswordViewController), forControlEvents: .TouchUpInside)
        // 背景
        view.backgroundColor = UIColor.whiteColor()
    }
    // MARK: - 懒加载
    /// logo
    private lazy var logoImageView:UIImageView = UIImageView(image: UIImage(named: "logo"))
    /// 账号输入框
    private lazy var userView: FormsView = {
        let fv = FormsView { (text) in
            // 赋值
            self.phoneNumber = text
        }
        // 区号
        fv.btn.setTitle("+86", forState: .Normal)
        fv.btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        fv.btn.titleLabel?.textAlignment = NSTextAlignment.Left
        fv.btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        fv.textField.placeholder = "请输入手机号码"
        return fv
    }()
    /// 密码输入框
    private lazy var passwordView: FormsView = {
        let fv = FormsView { (text) in
            // 赋值
            self.password = text
        }
        // 图片
        fv.btn.setImage(UIImage(named:"mobile"), forState: .Normal)
        fv.textField.placeholder = "请输入验证码"
        return fv
    }()
    /// 获取短信验证码按钮
    private lazy var getSMSBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("获取短信验证码", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(10)
        btn.titleEdgeInsets = UIEdgeInsetsMake(0, 1, 0, 1)
        btn.titleLabel?.adjustsFontSizeToFitWidth = true
        btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        btn.layer.cornerRadius = 10
        btn.layer.borderWidth = 1
        return btn
    }()
    /// 登录按钮
    private lazy var loginBtn: UIButton = UIButton.buttonWithColor("登录")
    /// or分割线左
    private lazy var orSplitLineLeft:UIView = UIView.splitLine(UIColor.tintColor())
    /// or分割线右
    private lazy var orSplitLineRight:UIView = UIView.splitLine(UIColor.tintColor())
    /// ORLabel
    private lazy var orLabel:UILabel = {
        let label = UILabel.creatLabel(color: UIColor.tintColor(), fontSize: 10)
        label.textAlignment = NSTextAlignment.Center
        label.text = "OR"
        return label
    }()
    /// 用户协议按钮
    private lazy var userAgreementBtn:UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named:"check"), forState: .Normal)
        btn.setTitle("用户协议", forState: .Normal)
        btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        return btn
    }()
    
    /// 密码登录按钮
    private lazy var passwordLoginBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("密码登录", forState: .Normal)
        btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        return btn
    }()


    
}
